import { Component, OnInit } from '@angular/core';

import { Storage } from '@ionic/storage';

import { NavController, ActionSheetController, AlertController } from 'ionic-angular';
import { Config } from '../../../providers/config';

import { Common } from '../../../providers/common';
import { DomSanitizer } from '@angular/platform-browser';
import _ from 'lodash';
import { MarketingMutualFundMonthlyService } from "./mfmonthly.service";

@Component({
    selector: 'page-marketing-mutulfund-monthly',
    templateUrl: './mfmonthly.html',

    providers: [MarketingMutualFundMonthlyService]
})
export class MarketingMutualFundMonthlyPage {
    moa_page_name: any = "page-marketing-mfmonthly";
    moa_page_explain: any = "互金月报";

    hasOpAuth = false
    tableData
    scaleTrendData //互金规模走势
    channelScaleData //渠道规模分布
    typeScaleChangeData //基金类型规模变动
    showleft = []
    constructor(public navCtrl: NavController,
        public alertCtrl: AlertController,
        public mfweeklyService: MarketingMutualFundMonthlyService,
        private sanitizer: DomSanitizer,
        private actionSheetCtrl: ActionSheetController,
        public storage: Storage,
        public common: Common
    ) {
    }

    ngAfterViewInit(): void {
        let loginid: string,
            org: string;
        this.storage.get("userInfo").then(user => {
            let that = this;
            loginid = user.loginid;
            org = user.orgname;
            let parmas = {
                "name": loginid,
                "titleid": 1003
            }
            this.mfweeklyService.getAnalyDataFromRedis(parmas).subscribe((res: any) => {
                if (res) {
                    this.hasOpAuth = res.isAdmin;
                    this.processData(res.requestData);
                }
            });
        });
    }

    processData(requestData) {

        console.log('------requestData------', requestData)
        this.tableData = requestData.data;

        _.forEach(this.tableData, item => {
            let leftItem = {
                "id": null,
                "col": [],
                "title": []
            }
            leftItem["id"] = item["option"]["id"];
            _.forEach(item.data, data => {
                _.forEach(data, (val, key) => {
                    if ((/[\u4e00-\u9fa5]+/).test(val) && key != "col8") {
                        leftItem.col.push(key)
                    }
                })
            })
            leftItem.col = _.uniq(leftItem.col);
            this.showleft.push(leftItem);
        })

        this.scaleTrendData = _.find(this.tableData, item => {
            return item['option']['id'] == 100028;
        });

        this.channelScaleData = _.find(this.tableData, item => {
            return item['option']['id'] == 100029;
        });

        this.typeScaleChangeData = _.find(this.tableData, item => {
            return item['option']['id'] == 100032;
        })
        if (this.scaleTrendData) {
            this.scaleTrend(this.scaleTrendData.data);
        }
        if (this.channelScaleData) {
            this.channelScale(this.channelScaleData.data);
        }
        if (this.typeScaleChangeData) {
            this.typeScaleChange(this.typeScaleChangeData.data);
        }


    }

    /**
     * 互金规模趋势图
     * @param datas 
     */
    scaleTrend(datas) {

        let scaleTrend_date = _.map(datas, "col1");
        let scaleTrend_datas = this.formatToNum(_.map(datas, "col2"));
        let digit = 1;

        if (datas && datas.length > 0) {
            let digitStr = String(datas[0]['col2'])
            let splotIndex = digitStr.indexOf('.');
            if (splotIndex > -1) {
                digit = digitStr.slice(splotIndex + 1).length;
            }
        }

        let elements = document.getElementsByClassName("scaleTrend");

        _.forEach(elements, el => {
            window["Highcharts"].chart({
                chart: {

                    renderTo: el
                },
                title: {
                    text: '',
                    style: {
                        "display": "none"
                    }
                },
                subtitle: {
                    text: "互金部规模走势（亿元)"
                },
                xAxis: {
                    type: "linear",
                    gridLineWidth: 0,
                    categories: scaleTrend_date
                },

                yAxis: {
                    gridLineWidth: 1,
                    gridLineDashStyle: 'longdash',
                    title: {
                        align: "high",
                        rotation: 0,
                        offset: 0,
                        y: -20,
                        x: 0,
                        text: ''
                    },
                    labels: {
                        format: '{value}'
                    }
                },
                navigation: {
                    buttonOptions: {
                        enabled: false
                    }
                },
                legend: {
                    enabled: false
                },

                tooltip: {
                    shared: true,
                    crosshairs: true,
                    valueDecimals: digit
                },

                plotOptions: {
                    series: {
                        cursor: 'pointer',
                        point: {
                            events: {
                                click: function (e) {

                                }
                            }
                        },

                    }
                },

                series: [{
                    name: '规模',
                    color: 'CornflowerBlue',
                    data: scaleTrend_datas
                }]

            });
        });
    }

    /**
     * 渠道规模
     * @param datas 
     */
    channelScale(datas) {
        let channelName_datas = _.map(datas, "topareaname");
        let channelScale_datas = this.formatToNum(_.map(datas, "col1"));
        let series_datas = [];

        let digit = 1;
        let digitData = datas[0].col1;
        let soptIndex = digitData.indexOf('.')
        if (soptIndex > -1) {
            digit = digitData.slice(soptIndex + 1).length
        }

        const columnColor = ["#f2725e", "#AFD8F8", "#8BBA00", "#FF8E46"]; //柱形图颜色预设
        channelScale_datas.forEach((item, index) => {
            let empt0bj = {};
            empt0bj['color'] = columnColor[index];
            empt0bj['y'] = item;
            series_datas.push(empt0bj);
        })

        let elements = document.getElementsByClassName("channelScale");
        _.forEach(elements, el => {
            window["Highcharts"].chart({
                chart: {
                    renderTo: el,
                    type: 'column'
                },
                title: {
                    text: ' '
                },
                subtitle: {
                    text: "互金部各渠道规模分布（亿元)"
                },
                xAxis: {
                    categories: channelName_datas
                },
                plotOptions: {
                    column: {
                        stacking: 'normal'
                    }
                },
                yAxis: {
                    title: {
                        align: "middle",
                        text: ''
                    }
                },
                navigation: {
                    buttonOptions: {
                        enabled: false
                    }
                },
                tooltip: {
                    valueDecimals: digit
                },
                legend: {
                    verticalAlign: 'top',
                    // margin: 35,
                    enabled: false
                },

                series: [{
                    name: '互金部各渠道规模分布',
                    data: series_datas
                }]
            });
        });
    }

    /**
     * 类型规模变动
     * @param datas 
     */
    typeScaleChange(datas) {
        let typeScaleChange_name = _.map(datas, "topareaname");
        let typeScaleChange_datas = this.formatToNum(_.map(datas, "col1"));
        let series_datas = [];
        let digitData = datas[0].col1;
        let percentSymbol = digitData.indexOf('%')
        let soptSymbol = digitData.indexOf('.')
        let digit = percentSymbol - soptSymbol - 1;

        _.forEach(typeScaleChange_name, (item, index) => {
            let emptArr = [];
            emptArr.push(item)
            emptArr.push(typeScaleChange_datas[index])

            series_datas.push(emptArr);
        })

        let elements = document.getElementsByClassName("typeScaleChange");
        _.forEach(elements, el => {
            window["Highcharts"].chart({
                chart: {
                    renderTo: el,
                    type: 'pie',
                    marginTop: 50
                },
                title: {
                    text: ' '
                },
                subtitle: {
                    text: "各基金类型规模变动"
                },
                tooltip: {
                    valueSuffix: '%',
                    valueDecimals: digit
                },
                plotOptions: {
                    pie: {
                        allowPointSelect: true,
                        cursor: 'pointer',
                        dataLabels: {
                            enabled: true,
                            formatter: function () {
                                return this.y.toFixed(digit) + '%';
                            },
                        },
                        showInLegend: true
                    }
                },
                navigation: {
                    buttonOptions: {
                        enabled: false
                    }
                },
                legend: {
                    //align: 'right',
                    verticalAlign: 'top',
                    //layout: 'vertical',
                    floating: true,
                    x: 0,
                    y: 20
                },
                series: [{
                    name: '各基金类型规模变动',
                    data: series_datas
                }]
            });
        });

    }

    setPosition(key, tableid) {

        let leftArr = _.find(this.showleft, { id: tableid })["col"];

        if (leftArr.indexOf(key) > -1) {
            return "showleft"
        }
    }

    getKeys(item) {
        return Object.keys(item);
    }
    /**
   * 更多操作
   */
    moreOp() {
        let bottons = [{
            text: '生成',
            handler: () => {
                this.storage.get("userInfo").then(user => {
                    let loginid = user.loginid;
                    let org = user.orgname;
                    let titleid: number = 1003;
                    this.mfweeklyService.generateUSPAnalyData(loginid, titleid).subscribe((res: any) => {
                        if (res) {
                            if (res.isSuccess) {
                                this.common.alertMessage("数据生成成功！");
                                this.processData(res.requestData);
                            } else {
                                this.common.alertMessage("数据生成失败！");
                            }
                        }
                    })
                });
            }
        }, {
            text: '发布',
            handler: () => {
                let confirm = this.alertCtrl.create({
                    title: '提示',
                    message: "您确定要发布吗？",
                    enableBackdropDismiss: false,
                    buttons: [{
                        text: '取消',
                        role: 'cancel',
                        handler: () => {

                        }
                    }, {
                        text: '确定',
                        handler: () => {
                            this.storage.get("userInfo").then(user => {
                                let loginid = user.loginid;
                                let org = user.orgname;
                                let titleid: number = 1003;
                                this.mfweeklyService.publishUSBMobileAnalyData(titleid).subscribe((res: any) => {
                                    if (res) {
                                        if (res.isSuccess) {
                                            this.common.alertMessage("数据发布成功！");
                                            this.processData(res.requestData);
                                        } else {
                                            this.common.alertMessage("数据发布失败！");
                                        }
                                    }
                                })
                            });
                        }
                    }]
                });
                confirm.present();
            }
        }, {
            text: '回滚',
            handler: () => {
                let confirm = this.alertCtrl.create({
                    title: '提示',
                    message: "您确定要回滚吗？",
                    enableBackdropDismiss: false,
                    buttons: [{
                        text: '取消',
                        role: 'cancel',
                        handler: () => {

                        }
                    }, {
                        text: '确定',
                        handler: () => {
                            this.storage.get("userInfo").then(user => {
                                let loginid = user.loginid;
                                let org = user.orgname;
                                let titleid: number = 1003;
                                this.mfweeklyService.rollBackUSBMobileAnalyData(titleid).subscribe((res: any) => {
                                    if (res) {
                                        if (res.isSuccess) {
                                            this.common.alertMessage("数据回滚成功！");
                                            this.processData(res.requestData);
                                        } else {
                                            this.common.alertMessage("数据回滚失败！");
                                        }
                                    }
                                })
                            });
                        }
                    }]
                });
                confirm.present();
            }
        }, {
            text: '取消',
            role: 'cancel',
            handler: () => {
            }
        }];

        let actionSheet = this.actionSheetCtrl.create({
            title: '',
            buttons: bottons
        });
        actionSheet.present();
    }

    formatToNum(datas) {
        let result = [];

        datas.forEach(item => {
            try {
                item = item.replace(/\%/g, '');
            } catch (err) {

            }
            result.push(Number(item));
        })
        return result;
    }
}


